import React, { memo, useCallback, useRef, useState } from "react";

const Button = memo(({onClick}:{onClick:()=>void}) => {
    console.log('button render')
    return <button onClick={onClick}>+1</button>
})

const useLatest = function<T>(val:T){
    const valRef = useRef(val)
    valRef.current = val
    return valRef
}

const CallbackUse = () => {
    const [count, setCount] = useState(0)
    console.log('render')

    const useEvent = (fn:(...args:unknown[])=>void) => {
        const fnRef = useLatest(fn)
        const event = useCallback((...args) => fnRef.current.apply(null, args), [])
        return event
    }

    const add = useEvent(()=>setCount(count + 1))

    return (
        <div>
            <h3>{count}</h3>
            <Button onClick={add} />
        </div>
    )
}

export default CallbackUse